package cn.wolfcode.luowowo.website.web.interceptor;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.web.annotation.RequireLogin;
import cn.wolfcode.luowowo.website.web.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CheckLoginInterceptor implements HandlerInterceptor {
    @Reference
    private IUserInfoRedisService userInfoRedisService;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = CookieUtil.getToken(request, response);
        UserInfo userInfo = userInfoRedisService.getUserInfo(token);
        if (handler instanceof HandlerMethod) {
            //如果该方法是HandlerMethod  说明需要拦截
            //并不是每个方法,都需要用户登录才能操作,所以进行贴自定义注解
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            if (handlerMethod.hasMethodAnnotation(RequireLogin.class)) {
                //如果贴了自定义注解,则判断用户是否登陆
                if (userInfo == null) {
                    //没有登陆,直接跳转到登录界面
                    response.sendRedirect("/login.html");
                    return false;
                }
            }
        }
        request.getSession().setAttribute("userInfo", userInfo);
        return true;
    }
}
